package com.yxhl.zoume.common.ui.activity;

import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.common.presenter.SplashPresenter;
import com.yxhl.zoume.common.ui.activity.base.BaseActivity;
import com.yxhl.zoume.common.ui.view.SplashObtionView;
import com.yxhl.zoume.core.main.info.MainEntrance;
import com.yxhl.zoume.core.main.model.MainEntranceInfo;
import com.yxhl.zoume.data.http.rest.response.splash.SplashResponse;
import com.yxhl.zoume.di.component.splash.DaggerSplashBannerComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.AppInfoUtils;
import com.yxhl.zoume.utils.DiskCacheUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.SplashUtils;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Xboy on 16/3/19.
 */
public class SplashActivity extends BaseActivity implements SplashObtionView {

    /**
     * 扉页动画时长
     */
    private static final int ANIMATION_LONG_INTERVAL = 3000;
    private static final int ANIMATION_SHORT_INTERVAL = 800;
    private static final String TAG = "SplashActivity";

    @BindView(R.id.iv_splash_icon)
    ImageView mSplash;
    @BindView(R.id.tv_splash_version)
    TextView mVersionTv;
    @BindView(R.id.iv_splash_publicity)
    ImageView mIvSplashPublicity;
    @BindView(R.id.iv_splash_jump)
    ImageView mIvSplashJump;
    @Inject
    SplashPresenter mSplashPresenter;

    //arguments
    private long mRecordTime;
    private PushAgent mPushAgent;
    private AlphaAnimation mAnimation;
    private MainEntranceInfo mMainEntranceInfo;
    private CountDownTimer mCountDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent();
        mRecordTime = System.currentTimeMillis();
        enableUMPush();
        mVersionTv.setText("v" + AppInfoUtils.getVersionName());
        mSplashPresenter.attachView(this);
        mSplashPresenter.obtionSplash(getScreen());
        showSplash();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //showSplash(mSplash);
        countDownShow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSplashPresenter.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSplashPresenter.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAnimation != null) {
            mAnimation.cancel();
        }
        mSplashPresenter.onDestroy();
        if (mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mMainEntranceInfo = (MainEntranceInfo) intent.getSerializableExtra(UIConstants.Push.INTENT_KEY_PUSH_INFO);
        }
    }

    /**
     * 开启友盟推送服务 获取到device token
     */
    private void enableUMPush() {
        mPushAgent = PushAgent.getInstance(ZouMeApplication.application);
        mPushAgent.onAppStart();

        //开启推送并设置注册的回调处理
        mPushAgent.enable(new IUmengRegisterCallback() {
            @Override
            public void onRegistered(final String registrationId) {

                LOG.e(TAG, "onRegistered deviceToken = " + registrationId + "deltaTime=" + (System.currentTimeMillis() - mRecordTime));
                enterApp();
            }
        });

        LOG.e(TAG, "updateStatus:" + String.format("enabled:%s  isRegistered:%s",
                mPushAgent.isEnabled(), mPushAgent.isRegistered()));

        LOG.e(TAG, "deviceToken: " + mPushAgent.getRegistrationId());
    }

    /**
     * 渐变展示启动页
     *
     * @param view
     */
    private void showSplash(View view) {
        if (view != null) {
            mAnimation = new AlphaAnimation(0.5f, 1.0f);
            String deviceToken = mPushAgent.getRegistrationId();
            if (deviceToken != null && deviceToken.length() >= 44) {
                mAnimation.setDuration(ANIMATION_SHORT_INTERVAL);
            } else {
                mAnimation.setDuration(ANIMATION_LONG_INTERVAL);
            }
            mAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                    // enterApp();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                }
            });

            view.startAnimation(mAnimation);
        } else {
            enterApp();
        }
    }

    private void enterApp() {
        if (mPushAgent != null) {
            String registrationId = mPushAgent.getRegistrationId();
            if (registrationId != null && registrationId.length() >= 44) {
                DiskCacheUtils.getInstance(SplashActivity.this).saveDeviceToken(registrationId);
            }
        }
        if (mMainEntranceInfo == null) {
            mMainEntranceInfo = new MainEntranceInfo<>(MainEntrance.SPLASH);
        }
        ZouMeApplication.application.getAppComponent().navigator().navigateToMain(this, mMainEntranceInfo);
        finish();
        overridePendingTransition(R.anim.noanimation, R.anim.noanimation);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.splash_activity;
    }


    @Override
    protected void initializeInjector() {
        DaggerSplashBannerComponent
                .builder()
                .activityModule(new ActivityModule(this))
                .appComponent(getAppComponent())
                .build()
                .inject(this);

    }

    public String getScreen() {
        int screenH;
        int screenW;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = getWindowManager().getDefaultDisplay();
            Point point = new Point();
            display.getRealSize(point);
            screenH = point.y;
            screenW = point.x;
        } else {
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            screenW = dm.widthPixels; //得到宽度
            screenH = dm.heightPixels; //得到高度
        }
        String screen = screenW + "*" + screenH;

        return screen;
    }

    @Override
    public void renderSplashOnSuccess(SplashResponse splashResponse) {
        showSplash();
    }

    @Override
    public void renderSplashOnFailure(String failureMsg) {
        mIvSplashPublicity.setClickable(false);
        PromptUtils.showShort(this, failureMsg);
    }

    @Override
    public void renderSplashOnError(String errorMsg) {
        mIvSplashPublicity.setClickable(false);
    }

    private void showSplash() {
        SplashUtils splashUtils = SplashUtils.getInstance(this);
        String imgUrl = splashUtils.getImgUrl();
        String targetUrl = splashUtils.getTargetUrl();

        if (TextUtils.isEmpty(imgUrl)) {
            imgUrl = "error";
        }

        if (TextUtils.isEmpty(targetUrl)) {
            mIvSplashPublicity.setClickable(false);
        } else {
            mIvSplashPublicity.setClickable(true);
        }
        mIvSplashPublicity.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Picasso.with(this)
                .load(imgUrl)
//                .placeholder(R.drawable.bg_splash)
//                .error(R.drawable.bg_splash)
                .into(mIvSplashPublicity);
        mAnimation = new AlphaAnimation(0.5f, 1.0f);
        String deviceToken = mPushAgent.getRegistrationId();
        if (deviceToken != null && deviceToken.length() >= 44) {
            mAnimation.setDuration(ANIMATION_SHORT_INTERVAL);
        } else {
            mAnimation.setDuration(ANIMATION_LONG_INTERVAL);
        }
        mSplash.startAnimation(mAnimation);


    }

    public void countDownShow() {
        mCountDownTimer = new CountDownTimer(3000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                enterApp();
            }
        }.start();
    }

    @OnClick({R.id.iv_splash_jump, R.id.iv_splash_publicity})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_splash_publicity: {
                SplashUtils splashUtils = SplashUtils.getInstance(this);
                String imgUrl = splashUtils.getImgUrl();
                String targetUrl = splashUtils.getTargetUrl();
                if (null == imgUrl || null == targetUrl) {
                    mIvSplashPublicity.setClickable(false);
                } else {
                    if (!"".equals(targetUrl)) {
                        navigator.navigateToAdActivity(this, targetUrl);
                    }
                    mCountDownTimer.cancel();
                    finish();
                }

            }
            break;
            case R.id.iv_splash_jump: {
                enterApp();
            }
            break;
        }
    }
}
